import request from '@/utils/request';

/**
 * 通用文件上传工具
 */
export interface UploadOptions {
  url: string; // 上传接口地址
  file: File | File[]; // 要上传的文件
  fileField?: string; // formData字段名，默认'file'
  data?: Record<string, unknown>; // 额外formData参数
  headers?: Record<string, unknown>; // 额外headers
}

export function upload(options: UploadOptions) {
  const {
    url,
    file,
    fileField = 'file',
    data = {},
    headers = {}
  } = options;

  const formData = new FormData();
  if (Array.isArray(file)) {
    file.forEach(f => formData.append(fileField, f));
  } else {
    formData.append(fileField, file);
  }
  Object.entries(data).forEach(([k, v]) => {
    formData.append(k, v as string | Blob);
  });

  return request.post(url, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      ...headers
    }
  }).catch(error => {
    console.error('文件上传失败:', error);
    throw error;
  });
}
